/*
 * Copyright 2007 Sam Hough
 * 
 * This file is part of GWTS.
 *
 * GWTS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * GWTS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GWTS.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.redspr.gwts;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.servlet.http.HttpServletResponse;

import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlElement;

public class HtmlElementHandler extends AbstractHandler {
    @Override
    void handle(Tryst tryst, DomNode node, HttpServletResponse res)
            throws IOException {
        PrintWriter out = res.getWriter();
        // TODO 00 super so can pick out onclick handler
        out.print("<");
        out.print(node.getNodeName());

        attr(tryst, (HtmlElement) node, out);
        kids(tryst, node, res);
    }

    void kids(Tryst tryst, DomNode node, HttpServletResponse res)
            throws IOException {
        kids(tryst, node, res, node.getNodeName());
    }

    void kids(Tryst tryst, DomNode node, HttpServletResponse res, String n)
            throws IOException {
        PrintWriter out = res.getWriter();
        Iterator it = node.getChildIterator();
        if (it.hasNext()) {
            out.print(">");
            while (it.hasNext()) {
                tryst.fix((DomNode) it.next(), res);
            }
            out.print("</" + n + ">");
        } else {
            out.print("/>");
        }
    }
}
